package zmee.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import kd.bos.bill.BillShowParameter;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.exception.KDBizException;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.CloseCallBack;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.list.ListShowParameter;
import kd.bos.print.api.PrintTask;
import kd.bos.print.api.PrintWork;
import kd.bos.print.core.service.PrtAttach;
import kd.bos.print.service.BosPrintServiceHelper;
import kd.bos.servicehelper.AttDto;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
* @author lijiawang
* @Date 2022/11/22 15:27
* @Description:
*/
public class BosUtil {
    private static Log logger = LogFactory.getLog(BosUtil.class);
    private static final DynamicObject download=OARequestUtil.getInitialize().config("download");

    //打开单据列表
    public static ListShowParameter openFormList(String entityName){
        ListShowParameter listShowParameter=new ListShowParameter ();
        listShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        listShowParameter.setBillFormId(entityName);
        return listShowParameter;
    }

    //打开单据列表
    public static BillShowParameter openForm(String entityName, String id){
        BillShowParameter billShowParameter=new BillShowParameter ();
        billShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        billShowParameter.setFormId(entityName);
        billShowParameter.setPkId(id);
        billShowParameter.setCloseCallBack(new CloseCallBack());
        return billShowParameter;
    }


    //上传附件
    public static void setAttachment(InputStream fileStream, DynamicObject srcbillo, String name,String attname) throws Exception{
        if(srcbillo==null){
            return;
        }
        DynamicObject srcbill = BusinessDataServiceHelper.loadSingle(srcbillo.getPkValue(), srcbillo.getDynamicObjectType().getName());
        Map<String,Object> params=new HashMap();
        params.put("formNumber",srcbill.getDynamicObjectType().getName());// 目标单据标识
        params.put("billPkId",srcbill.getPkValue());//目标单据PkId
        Map<String,Object> map=new HashMap();
        List<AttDto> list=new ArrayList<>();

            FileService fs= FileServiceFactory.getAttachmentFileService();
            String path = "/"+srcbill.getDynamicObjectType().getName()+"/attachmentpanel/"+name;
            int size=fileStream.available();
            logger.info("size:"+size);
            FileItem fi = new FileItem(name,path,fileStream);

            fi.setCreateNewFileWhenExists(true);
            String paths= fs.upload(fi);
            //获取实际存储路径
            String realPath = FileServiceFactory.getAttachmentFileService().getFileServiceExt().getRealPath(paths);
            logger.info("==realPath=="+realPath);
            logger.info("path:"+paths);
            AttacUpdate(srcbillo,name,realPath,size,attname);
    }

    public static void AttacUpdate(DynamicObject pkid,String fileName,String uploadPath,int size,String attname){
        Map uploadFileMap = new HashMap();
        uploadFileMap.put("entityNum", pkid.getDynamicObjectType().getName());
        uploadFileMap.put("billPkId", pkid.toString());
        uploadFileMap.put("lastModified", new Date().getTime());

        StringBuffer uid = new StringBuffer();
        long time = new Date().getTime();
        uid.append("rc-upload-");
        uid.append(time);
        uid.append("-");
        uid.append("1");
        uploadFileMap.put("uid", uid.toString());
        uploadFileMap.put("name", fileName);
        uploadFileMap.put("url", uploadPath);
        uploadFileMap.put("size", size);
        uploadFileMap.put("status", "success");

        List<Map<String, Object>> attachments = new ArrayList<>();
        attachments.add(uploadFileMap);

        AttachmentServiceHelper.upload(pkid.getDynamicObjectType().getName(), pkid.getPkValue(), attname, attachments);

    }

    //获取编码规则
    public static String getNumber(DynamicObject sl){
        CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(sl.getDataEntityType().getName(), sl, null);
        return CodeRuleServiceHelper.getNumber(codeRule, sl);
    }



    //获取token密钥
    public static String getIerpAppToken(DynamicObject ierp){

        logger.info("====data==="+ierp);
        JSONObject map=new JSONObject();
        map.set("appId",ierp.getString("user"));
        map.set("appSecuret",ierp.getString("password"));
        map.set("accountId",ierp.getString("accountid"));
        String secreturl = ierp.getString("secreturl");
        try {
            logger.info("====secreturl==="+secreturl);
            logger.info("====密钥map==="+map);
            String url = HttpRequestUtil.getResult(secreturl, map.toString());
            logger.info("====da==="+url);
            JSONObject jsonObject = JSONUtil.parseObj(url);
            JSONObject data = jsonObject.getJSONObject("data");
            return data.get("app_token").toString();
        }catch (Exception e){
            logger.info("====token==="+e);
        }
        return null;
    }
//获取登入token
    public static String getLoginToken(){
        DynamicObject ierp=OARequestUtil.getInitialize().config("ierp");
        logger.info("===登入码ierp==="+ierp);
        JSONObject map=new JSONObject();
        map.set("user","administrator");
        map.set("apptoken",getIerpAppToken(ierp));
        map.set("accountId",ierp.getString("accountid"));
        String tokenurl = ierp.getString("tokenurl");
        try {
            logger.info("===登入码tokenurl==="+tokenurl);
            logger.info("===登入码map==="+map);
            String body = HttpRequestUtil.getResult(tokenurl, map.toString());
            logger.info("===data==="+body);
            JSONObject jsonObject = JSONUtil.parseObj(body);
            JSONObject data = jsonObject.getJSONObject("data");
            return data.get("access_token").toString();
        }catch (Exception e){
            logger.info("===登入码获取失败==="+e);
        }
        return null;

    }

    //附件生成
    public static void createAtt(String byNumber, IDataModel model , IFormView view, String attachKey, String formId){
        if(byNumber!=null && !"".equals(byNumber)) {
            //1.根据模板生成附件
            //通过模版编码获取模版ID
            String tplId = BosPrintServiceHelper.getTplIdByNum(byNumber);
            //构造打印服务接口需要的参数 PrintWork
            PrintWork work = new PrintWork();
            //设置打印语言
            work.setPrintLang("zh_CN");
            //设置类型：1代表pdf
            work.setExpType("1");
            List<PrintTask> printTasks = new ArrayList<>();
            PrintTask printTask = new PrintTask();
            printTask.setTplId(tplId);//设置模板ID
            //获取当前单据PKID
            Object id = model.getValue("id");
            //设置当前单据PKID
            printTask.setPkIds(new ArrayList<Object>(Arrays.asList(id)));
            printTask.setPrintType("billForm");
            printTask.setFormId("src_decision");
            printTasks.add(printTask);
            work.setTaskList(printTasks);
            try {
                //调用打印服务接口
                PrtAttach prtAttach = BosPrintServiceHelper.doPrint(work);
                logger.info("==prtAttach==" + prtAttach);
                //获取生成的pdf在文件服务器中的路径
                PrtAttach.AttachDetail attachDetail = prtAttach.getAttachDetail().get(0);
                logger.info("==path==" + attachDetail);

                List<Map<String, Object>> atts = new ArrayList<Map<String, Object>>();
                atts.add(createAttInfo(attachDetail, model.getValue("billno").toString()));
                //上传附件到采购订单的附件面板中
                AttachmentServiceHelper.upload(formId, id, attachKey, atts);

                view.updateView();
            } catch (Exception e) {
                throw new KDBizException(e.getMessage());
            }
        }
    }

    //构建附件面板信息
    private static Map<String, Object> createAttInfo(PrtAttach.AttachDetail attachDetail, String billno) {

        Map<String, Object> att = new HashMap<String, Object>();
        // 当前时间戳
        long time = new Date().getTime();

        att.put("createdate", time);
        // lastModified:时间戳
        att.put("lastModified", time);
        att.put("status", "success");
        String attType = attachDetail.getFileType();
        att.put("type", attType);
        // name:文件名(含文件格式)
        att.put("name", billno+attachDetail.getFileName());
        FileService fs = FileServiceFactory.getAttachmentFileService();
        InputStream in = fs.getInputStream(attachDetail.getFilePath());
        try {
            // 附件大小
            byte[] AttByte = InputStreamToByte(in);
            att.put("size", AttByte.length);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        StringBuffer uid = new StringBuffer();
        uid.append("rc-upload-");
        uid.append(time);
        uid.append("-");
        uid.append("1");
        att.put("uid", uid.toString());
        att.put("url", attachDetail.getFilePath());
        return att;
    }

    // ImputStream输入流转二进制数据
    public static byte[] InputStreamToByte(InputStream in) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = in.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }


}
